package web.servlet;

import domain.User;
import org.apache.commons.beanutils.BeanUtils;
import service.UserService;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @author Mc.Chai
 * @program: JavaWeb
 * @create 2022-04-01-16:53 16:53
 */
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码格式
        request.setCharacterEncoding("utf-8");
        //获取表单中填写的数据
        String verifycode = request.getParameter("verifycode");
        //获取验证码的session数据
        HttpSession session = request.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        session.removeAttribute("CHECKCODE_SERVER");
        //进行验证码的验证(忽略大小写)
        if (checkcode_server!=null && checkcode_server.equalsIgnoreCase(verifycode)){
            //验证码正确
            //封装user对象
            Map<String, String[]> map = request.getParameterMap();
            User user = new User();
            try {
                //将用户名和密码封装成user对象（只有用户名密码）
                BeanUtils.populate(user,map);
                //进行用户名和密码的验证
                UserService userService=new UserServiceImpl();
                User login_user = userService.login(user);
                if (login_user!=null){
                    //登录成功
                    //将用户的信息存储到session数据域中
                    session.setAttribute("login_user",login_user);
                    //跳转页面
                    response.sendRedirect(request.getContextPath()+"/index.jsp");
                }else{
                    //用户名或密码错误
                    //将错误信息存储到session域中
                    session.setAttribute("login_error","用户名或密码错误");
                    request.getRequestDispatcher("/login.jsp").forward(request,response);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }else{
            //验证码失败
            session.setAttribute("login_error","验证码输入有误");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
